<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header flexAic">
          <span>付款钱包</span>

          <el-tooltip class="box-item" effect="dark" placement="bottom">
            <template #content>
              付款钱包记录了各类订单的收入与支出，其中专家后台与小程序的订单收益会流入“自营钱包”；
              <br />
              代收钱包的收入可被提现，自营钱包的收入仅做记录不可提现。
              <br />
            </template>
            <img
              style="width: 20px; margin-left: 10px"
              src="https://b.gaokaow.cc/question@2x.png"
              alt=""
            />
          </el-tooltip>
          <span class="ml20 fz14"
            >钱包余额 <span class="money">{{ storeBalance }}</span> 元
          </span>
          <div class="ml20 cBlue fz14 curr" @click="toRecharge">
            去充值
            <el-icon style="vertical-align: middle"
              ><ArrowRightBold style="width: 20px; height: 20px"
            /></el-icon>
          </div>
        </div>
      </template>
      <navTop
        :dataList="list"
        :incomeData="incomeData"
        @menuBtn="menuBtn"
        @yearChange="yearChange"
        :menuList="menuList"
        :title="title"
      ></navTop>
      <div class="myChart">
        <div id="myChart" style="width: 100%; height: 330px">
          <EChartWrapper :type="'line'" :options="lineChartOptions" />
        </div>
      </div>
    </el-card>

    <bottom
      title="付款"
      :loading="loading"
      :tableData="tableData"
      @serchSelect="handleSeach"
      :params="tableConfig"
      @sizeChange="sizeChange"
      @currentChange="currentChange"
      @sort="sort"
    ></bottom>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import EChartWrapper from '@/components/ECharts';
import { computed, nextTick, onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import navTop from '../components/nav.vue';
import bottom from '../components/bottom.vue';
import withdraw from '@/modules';
import paymentWallet from '@/modules';
const { getMoneyLogList, monExpenditure } = paymentWallet;
const { accountBalanceApi } = withdraw;
const storeBalance = ref('');
const title = ref('支出概览');
const echarsData = ref({});
const tableData = ref([]);
const list = ref([]);
const loading = ref(true);
const dataList = ref([
  {
    name: '支出总计',
    money: '',
  },
  {
    name: '购买应用',
    money: '',
  },
  {
    name: '开通VIP',
    money: '',
  },
  {
    name: '志愿填报',
    money: '',
  },
  {
    name: '短信',
    money: '',
  },
  {
    name: '购买账号',
    money: '',
  },
  {
    name: '志愿卡',
    money: '',
  },
  {
    name: '升学卡',
    money: '',
  },
]);
const menuList = ref([
  {
    type: 1,
    label: '支出概览',
  },
  {
    type: 2,
    label: '收入概览',
  },
]);

const incomeData = ref([
  {
    name: '支出总计',
    money: '',
  },
  {
    name: '机构充值',
    money: '',
  },
  {
    name: '客服代充',
    money: '',
  },
  {
    name: '退还客单费',
    money: '',
  },
  {
    name: '系统赠送',
    money: '',
  },
]);

const params = ref({
  page: 1,
  pageSize: 20,
  dateType: -1,
  type: 1,
  walletType: 1,
});
const tableConfig = ref({
  walletType: 1,
  page: 1,
  pageSize: 20,
  total: null,
});
//排序
const sort = (val) => {
  tableConfig.value.sort = val.sort;
  tableDataList();
};

const yearChange = (e) => {
  params.value.dateType = e.dateType;
  params.value.year = e.year;
  params.value.type = e.type ? e.type : params.value.type;
  topDataList();
};
const sizeChange = (val) => {
  loading.value = true;
  tableConfig.value.pageSize = val;
  tableDataList();
};
const currentChange = (val) => {
  loading.value = true;
  tableConfig.value.page = val;
  tableDataList();
};
const menuBtn = (val) => {
  params.value.type = val.value.type;
  topDataList();
};

// 格式转换
const formatCurrency = (num) => {
  const cleanedNum = Number(num.toString().replace(/,/g, ''));
  return new Intl.NumberFormat('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(cleanedNum);
};

const lineData = ref({});
const topDataList = async () => {
  await monExpenditure(params.value).then(({ data }) => {
    lineData.value = data.financeStatPic;
    let arr = [];
    const total = formatCurrency(data.total);
    if (params.value.type == 1) {
      const app = formatCurrency(data.app);
      const duanXin = formatCurrency(data.duanXin);
      const zhiYuanTianBao = formatCurrency(data.zhiYuanTianBao);
      const IsVip = formatCurrency(data.vip);
      const zhiYuanKa = formatCurrency(data.zhiYuanKa);
      const shengXueKa = formatCurrency(data.shengXueKa);
      const accountTotal = formatCurrency(data.accountTotal);
      arr = [
        total,
        app,
        IsVip,
        zhiYuanTianBao,
        duanXin,
        accountTotal,
        zhiYuanKa,
        shengXueKa,
      ];
      arr.forEach((value, index) => {
        if (index < dataList.value.length) {
          dataList.value[index].money = value.toString();
          list.value = dataList.value;
        }
      });
    } else {
      let arr2 = [];
      const online = formatCurrency(data.online);
      const kf = formatCurrency(data.kf);
      const tk = formatCurrency(data.tk);
      const giveAway = formatCurrency(data.giveAway);
      arr2 = [total, online, kf, tk, giveAway];
      arr2.forEach((value, index) => {
        if (index < incomeData.value.length) {
          incomeData.value[index].money = value.toString();
          list.value = incomeData.value;
        }
      });
    }
    const xAxis = data.financeStatPic.times.map((item) => item + '月');
    const yAxis = data.financeStatPic.money;
    nextTick(() => {
      echarsData.value = [xAxis, yAxis];
    });
  });
};

const tableDataList = () => {
  getMoneyLogList(tableConfig.value).then((res) => {
    const { data } = res;
    tableData.value = data.data;
    tableConfig.value.total = data.total;
    loading.value = false;
  });
};

const handleSeach = (val) => {
  loading.value = true;
  tableConfig.value = val;
  tableDataList();
};

const router = useRouter();

const toRecharge = () => {
  router.push({
    path: '/financialMan/rechargeManage',
  });
};
const lineChartOptions = ref({
  title: [
    {
      // 标题
      text: computed(() =>
        params.value.type == 1 ? '营业支出(元)' : '营业收入(元)'
      ),
    },
  ],
  xAxis: {
    type: 'category',
    data: computed(() => lineData.value.times),
    //刻度相关配置：
    axisTick: {
      show: false, //去掉刻度
    },
    axisLine: {
      lineStyle: {
        color: 'rgb(229,230,235)', // X轴线的颜色
        width: 2, // X轴线的宽度
      },
    },
    //轴
    axisLabel: {
      formatter: '{value}', // 显示单位为 "w"
    },
  },
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      var value = params[0].value;
      var color = value ? 'rgb(40,90,250)' : ''; // 根据数据值设置字体颜色
      var p = `<p>${params[0].axisValue} 营业支出（元）</p>`;
      return p + '<span style="color:' + color + '">' + value + '</span>';
    },
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: function (value) {
        return value >= 10000 ? (value / 10000).toFixed(1) : value; // 将超过10000的值转化为"w"单位
      },
      color: 'rgb(229,230,235)', // y轴线的颜色
    },
  },
  series: [
    {
      type: 'line',
      smooth: true,
      data: computed(() => lineData.value.money),
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(90, 177, 239, 0.5)' },
          { offset: 1, color: 'rgba(90, 177, 239, 0)' },
        ]),
      },
    },
  ],
});
//账户余额
const getUserMoney = async () => {
  try {
    const { data } = await accountBalanceApi();
    storeBalance.value = formatCurrency(data.storeBalance);
  } catch (error) {
    console.log('error:', error);
  }
};
onMounted(() => {
  topDataList();
  tableDataList();
  getUserMoney();
});
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';
@import '@/assets/styles/global.scss';
.flexAic {
  display: flex;
  align-items: center;
}

.cBlue {
  color: $light-blue;
}
.money {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary-color);
}
.fz14 {
  font-size: 14px;
  font-weight: 400;
  color: #86909c;
  color: var(--text-secondary-color);
}
.curr {
  color: var(--primary-color);
}
</style>
